package moe.launch;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.regex.Pattern;

public class RuleClassLoader extends URLClassLoader {
	private Pattern[] patterns;

	private RuleClassLoader(URL[] urls, String[] rules) {
		super(urls);
		if (rules == null) {
			return;
		}
		int length = rules.length;
		patterns = new Pattern[length];
		for (int i = 0; i < length; i++) {
			patterns[i] = Pattern.compile(rules[i]);
		}
	}

	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {
		Class<?> result = findLoadedClass(name);
		if (result == null && patterns != null) {
			for (Pattern p : patterns) {
				if (p.matcher(name).matches()) {
					result = this.findClass(name);
					break;
				}
			}
		}
		if (result == null) {
			result = super.loadClass(name);
		}
		return result;
	}

	public static ClassLoader createClassLoader(String[] rules) {
		String pathString = System.getProperty("java.class.path");
		String[] paths = pathString.split(";");
		int length = paths.length;
		URL[] urls = new URL[length];
		try {
			for (int i = 0; i < length; i++) {
				File file = new File(paths[i]);
				urls[i] = file.toURI().toURL();
			}
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
		return new RuleClassLoader(urls, rules);
	}
}
